import service from "@/utils/request";
import { createStore } from "vuex";

export default createStore({
    state: {
        isLogin: false,
        token: null,
        activeIndex: "",
        userInfo: {},
    },
    getters: {},
    mutations: {
        setUserInfo(state) {
            service({
                method: "get",
                url: "/getInfoByToken",
                headers: {
                    token: state.token,
                },
            }).then((res) => {
                state.userInfo = { ...res.data };
                // console.log(state.userInfo);
                localStorage.setItem("userInfo", JSON.stringify(state.userInfo));
            });
        },
        getUserInfo(state) {
            // console.log(state.userInfo);
            state.userInfo = JSON.parse(localStorage.getItem("userInfo"));
        },
        setActiveIndex(state, activeIndex) {
            state.activeIndex = activeIndex;
            localStorage.setItem("activeIndex", state.activeIndex);
        },
        getActiveIndex(state) {
            state.activeIndex = localStorage.getItem("activeIndex");
        },
        checkLogin(state) {
            state.token = localStorage.getItem("token");
            state.isLogin = state.token !== null;
            service({
                method: "get",
                url: "/getInfoByToken",
                headers: {
                    token: state.token,
                },
            }).then((res) => {
                // console.log(res.ok);
                state.isLogin = res.ok;
            });
        },
        setToken(state, token) {
            state.token = token;
            localStorage.setItem("token", state.token);
        },
        logout(state) {
            localStorage.removeItem("token");
            state.token = null;
            localStorage.removeItem("userInfo");
            state.userInfo = null;
            window.location.reload();
            checkLogin();
        },
    },
    actions: {},
    modules: {},
});
